from flask import Blueprint, Response, request
import json
import re
import Net


api_mm131 = Blueprint('api_mm131', __name__)

mm_host = 'http://www.mm131.com/'
image_host = 'http://img10.mm798.net/'
classify = ['qingchun', 'xiaohua', 'chemo', 'qipao', 'mingxing', 'xinggan']
classify_zh = ['清纯美眉', '美女校花', '性感车模', '旗袍美女', '明星写真', '性感美女']


class Result:

    def __init__(self, state='error', msg='', zh='', data=None):
        self.state = state
        self.msg = msg
        self.zh = zh
        if data is None:
            self.data = []
        else:
            self.data = data

    def json(self):
        result = json.dumps(self.__dict__, ensure_ascii=False)
        return Response(response=result, mimetype='application/json')


class Bean:

    def __init__(self, title, image, tag, href, router=None):
        self.title = title
        self.image = image
        self.tag = tag
        self.href = href
        self.router = router


@api_mm131.route('/')
def index():
    return ''


@api_mm131.route('/<int:type>/page/<int:page>')
def get_data(type, page):

    url = mm_host + classify[type]
    tag = classify_zh[type]

    if page > 1:
        url = mm_host + classify[type] + '/list_' + str(type + 1) + '_' + str(page) + '.html'

    respond = Net.get_html(url)
    respond.encoding = 'gb2312'

    pattern = re.compile('<a target="_blank" href="(.*?)"><img src="(.*?)" alt="(.*?)" width="120".*?</a>', re.S)
    data = re.findall(pattern, respond.text)

    # print(respond.text)

    array = []
    for item in data:
        bean = Bean(item[2], re.sub('http://img1.mm131.me/', image_host, item[1]), tag, item[0])
        array.append(bean.__dict__)
        # print(item[0], item[2])
    return Result('success', 'get data success', '获取数据成功', array).json()


@api_mm131.route('/list')
def get_list():

    url = request.args.get('url')

    num = re.findall('//.*?/.*?/(.*?).html', url)
    host = image_host + 'pic/' + num[0] + '/@.jpg'

    respond = Net.get_html(url)
    respond.encoding = 'gb2312'

    pattern = re.compile('<span class="page-ch">共(.*?)页</span>', re.S)

    page = re.findall(pattern, respond.text)[0]

    # print(page)

    array = []
    for i in range(1, int(page)+1):
        image = re.sub('@', str(i), host)
        array.append(image)
        # print(image)

    return Result('success', 'get data success', '获取数据成功', array).json()
